﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Reflection;

namespace Neoit.Utils
{
    /// <summary>
    /// DataTable
    /// </summary>
    public static class DataTableHelper
    {
        /// <summary>
        /// 将泛型集合类转换成DataTable
        /// </summary>
        /// <typeparam name="T">集合项类型</typeparam>
        /// <param name="list">集合</param>
        /// <param name="tableName">表名</param>
        /// <returns>数据集(表)</returns>
        public static DataTable ToDataTable<T>(this IList<T> list, string tableName = null)
        {
            var result = new DataTable(tableName);
            if (list.Count <= 0)
            {
                return result;
            }

            var properties = list[0].GetType().GetProperties();
            result.Columns.AddRange(properties.Select(p =>
            {
                if (p.PropertyType.IsGenericType && p.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
                {
                    return new DataColumn(p.GetCustomAttribute<DescriptionAttribute>()?.Description ?? p.Name, Nullable.GetUnderlyingType(p.PropertyType));
                }

                return new DataColumn(p.GetCustomAttribute<DescriptionAttribute>()?.Description ?? p.Name, p.PropertyType);
            }).ToArray());
            foreach (var item in list)
            {
                result.LoadDataRow(properties.Select(p => p.GetValue(item)).ToArray(), true);
            }
            return result;
        }
        /// <summary>
        /// 将DataTable转为集合
        /// </summary>
        public static List<T> ToList<T>(this DataTable dt) where T : new()
        {
            var ts = new List<T>();
            foreach (DataRow dr in dt.Rows)
            {
                T t = new T();
                PropertyInfo[] propertys = t.GetType().GetProperties();
                foreach (PropertyInfo pi in propertys)
                {
                    string propertyName = pi.Name;
                    if (dt.Columns.Contains(propertyName))
                    {
                        if (!pi.CanWrite) continue;
                        object value = dr[propertyName];
                        if (value != DBNull.Value) pi.SetValue(t, value, null);
                    }
                }
                ts.Add(t);
            }
            return ts;
        }
    }
}
